package com.dst.smart.handler.disposer;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dst.smart.app.MainActivity;
import com.dst.smart.handler.entity.SemanticResult;
import com.dst.smart.handler.entity.ServiceType;
import com.dst.smart.music.MusicPlayMedia;
import com.dst.smart.player.entity.SongPlayInfo;

import android.content.Context;
import android.util.Log;

/**
 * 	新闻结果处理器。
 * 	给我讲个新闻
 	我想看体育新闻
 	有什么社会新闻
 * author <a href="http://www.xfyun.cn">讯飞开放平台</a>
 * date 2016年9月5日 下午4:58:10
 *
 */
public class NewsDisposer extends Disposer {
	private static final String KEY_URL = "url";

	public NewsDisposer(Context context) {
		super(context);
	}
	
	@Override
	public void disposeResult(final SemanticResult semanticResult) {
		try {
			if (semanticResult != null) {
				final List<SongPlayInfo> playList = new ArrayList<SongPlayInfo>();
				Log.e("text", "News" + semanticResult.getAnswerText());
				JSONArray result = semanticResult.getResult();
				if (result != null && result.length() != 0) {
					if (MainActivity.musicIsSong) {
						for (int i = 0; i < result.length(); i++) {
							JSONObject newsJson = result.optJSONObject(i);
							String url = newsJson.getString(KEY_URL);
							String title = newsJson.getString("title");
							SongPlayInfo playInfo = new SongPlayInfo();
							playInfo.setAnswerText(title);
							playInfo.setPlayUrl(url);
							playList.add(playInfo);
						}

						try {
							if (MusicPlayMedia.getInstansMedia() == null) {
								new MusicPlayMedia(mContext, "");
							}
							MusicPlayMedia.getInstansMedia().playURLList(playList);
							MusicPlayMedia.getInstansMedia().setFileName(1,
									playList.get(0).getPlayUrl(), 1);
							MusicPlayMedia.getInstansMedia().play();
							if (semanticResult.getAnswerText().length() > 0) {
								//先播放標題
								getPlayController().playURLList(semanticResult.getUUID(), null);
								getPlayController().playText(semanticResult.getUUID(), semanticResult.getAnswerText(), true, "", null);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
					sendAiuiData("新闻", "news", result.toString());
				} else {
					getPlayController().playURLList(semanticResult.getUUID(), null);
					getPlayController().playText(semanticResult.getUUID(), semanticResult.getAnswerText(), true, "", null);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		/*getPlayController().playText(result.getUUID(), result.getAnswerText(), 
				false, new Runnable() {
			
			@Override
			public void run() {
				getPlayController().playURLList(result.getUUID(), playList);
			}
		});*/
	}
	
	public boolean canHandle(ServiceType type){
		return (type == ServiceType.NEWS);
	}
}
